package org.ezplatform.office.meeting.info.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.QSMeetingInfo;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.office.meeting.info.dao.QSMeetingDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 全时会议
 * @author sj
 *
 */
@Service("QSMeetingService")
@Transactional
public class QSMeetingService extends BaseService<QSMeetingInfo, String>{
	
     private final Logger logger = LoggerFactory.getLogger(QSMeetingService.class);
     @Lazy
     @Autowired
 	 private ApplyRecordService service;
     @Lazy
     @Autowired
 	 private QSMeetingService qsMeetingService;
     @Lazy
 	 @Autowired
 	 private QSUserService qsUserService;
 	
     @Autowired
 	 private QSMeetingDao qSMeetingDao;

 	 @Override
 	 protected JpaBaseDao<QSMeetingInfo, String> getEntityDao() {
 		return this.qSMeetingDao;
 	 }
 	 
 	 public int deleteByRecordId(String... applyRecordId){
		return this.qSMeetingDao.deleteByRecordId(applyRecordId);
	 }
 	
 	 /**
 	  * 保存信息
 	  * @param list
 	  * @return
 	  */
 	 public QSMeetingInfo saveQSMeetingInfo(QSMeetingInfo info) {
 		logger.debug("---saveQSMeetingInfo--");
 		
		return super.save(info);
	 }
 	 /**
 	  * 删除全时会议记录
 	  * @param meetingApplyId
 	  */
 	 public void delQSMeetingInfo(String meetingApplyId) {
 		logger.debug("---delQSMeetingInfo--");

        StringBuffer sql = new StringBuffer("select id from oa_meeting_qs where meetingApplyId =:meetingApplyId ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("meetingApplyId", meetingApplyId);
        List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
        if(list!=null&&list.size()>0) {
        	QSMeetingInfo info = null;
             for(int i=0;i<list.size();i++) {
            	 info = new QSMeetingInfo();
            	 info.setId(list.get(0).get("id")+"");
            	 super.delete(info);
             }
        }

	 }
 	 
 	/**
  	 * 获取Pc会议链接
  	 * @param meetingApplyId
  	 * @return
  	 */
  	public Map getQsMeetingUrlById(String meetingApplyId) {
     	logger.debug("-----------------getQsMeetingUrlById-------");
         StringBuffer sql = new StringBuffer("select emeeUrl,attendUrl from oa_meeting_qs where meetingApplyId =:meetingApplyId ");
         Map<String, Object> paramMap = new HashMap<String, Object>();
         paramMap.put("meetingApplyId", meetingApplyId);
         List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
         if(list!=null&&list.size()>0) {
            return (Map) list.get(0);
         }else {
         	return null;
         }
     }
  	/**
  	 * 获取全时会议id
  	 * @param meetingApplyId
  	 * @return
  	 */
  	public Map getQsMeetingInfoByMeetingId(String meetingApplyId) {
     	 logger.debug("-----------------getQsMeetingInfoByMeetingId-------");
         StringBuffer sql = new StringBuffer("select id,conferenceId from oa_meeting_qs where meetingApplyId =:meetingApplyId ");
         Map<String, Object> paramMap = new HashMap<String, Object>();
         paramMap.put("meetingApplyId", meetingApplyId);
         List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
         if(list!=null&&list.size()>0) {
            return (Map) list.get(0);
         }else {
            return null;
         }
     }
  	
  	/**
	 * 新增网络会议
	 * @return
	 * @throws Exception 
	 */
  	public Map newQSMeeting(String meetingApplyName,
							          String startTime,
							          String endTime,
							          String curUserId,
							          String token) throws Exception {
  		
  		logger.debug("-----------------newQSMeeting-------------------");
  		Map res = new HashMap();

		String siteUrl = getQSSysINfo(token);
		logger.debug("siteUrl:"+siteUrl);
        
		//新增
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		//用创建人发起全时会议
		String qsUid = qsUserService.getQsUserAcc(curUserId);
		logger.debug("-qsUid:"+qsUid);
		
		String d1 = startTime;
		String d2 = endTime;
		logger.debug("-d1:"+d1);
		logger.debug("-d2:"+d2);
		
		Date date1 = df.parse(d1);
		Date date2 = df.parse(d2);
		
		long date1long = date1.getTime();  
	    long date2long = date2.getTime();  
	    int min = (int) ((date2long - date1long) / (1000 * 60));  
	    logger.debug("-min:"+min);
		
		if(qsUid!=null&&!"".equals(qsUid)) {
			
			//预约全时会议
			Map qsMap = qsUserService.reservConference(qsUid, meetingApplyName, min+"", date1,siteUrl);
			if("0".equals(qsMap.get("success"))) {
				logger.debug("--newQSMeeting-success----");
				QSMeetingInfo info = new QSMeetingInfo();
//				info.setMeetingApplyId(meetingApplyId);
//				info.setEmceeUser(emceeUserId);
				info.setEmeeUrl(qsMap.get("hostConferenceUrl")+"");
				info.setAttendUrl(qsMap.get("attendeeJoinUrl")+"");
				info.setConferenceId(qsMap.get("conferenceId")+"");
				info.setPcode1(qsMap.get("pcode1")+"");
				info.setPcode2(qsMap.get("pcode2")+"");
				res.put("info", info);
				res.put("success", "0");

//				qsMeetingService.saveQSMeetingInfo(info);
				logger.debug("---全时会议预约成功！---");
			}else {
				res.put("info", null);
				res.put("success", "-1");
				res.put("msg", "add false:"+qsMap.get("err"));
			}
		}
		return res;
	}
  	
	/**
	 * 修改网络会议
	 * @return
	 */
	public String updateQSMeeting(String oldId,
			                        ApplyRecord newEntity,
							        String oldUserId,
							        String token) throws Exception {
		logger.debug("-----------------updateQSMeeting-------------------");
		String res = "0";

		String siteUrl = getQSSysINfo(token);
		logger.debug("siteUrl:"+siteUrl);
        
		//新增
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		
		//String emceeUserId = this.service.getEmceeUser(newEntity);
		
		String d1 = newEntity.getStartTime();
		String d2 = newEntity.getEndTime();
		//logger.debug("-emceeUserId:"+emceeUserId);
		logger.debug("-d1:"+d1);
		logger.debug("-d2:"+d2);
		
		Date date1 = df.parse(d1);
		Date date2 = df.parse(d2);
		
		long date1long = date1.getTime();  
	    long date2long = date2.getTime();  
	    int min = (int) ((date2long - date1long) / (1000 * 60));  
	    logger.debug("-min:"+min);
		
		//用创建人发起全时会议
		String qsUid = qsUserService.getQsUserAcc(oldUserId);
		
		Map qsInfo = qsMeetingService.getQsMeetingInfoByMeetingId(oldId);
		String conferenceId = qsInfo.get("conferenceId")+"";
		String qsId = qsInfo.get("id")+"";
		
		if(conferenceId!=null&&!"".equals(conferenceId)) {
			
			//预约全时会议
			Map qsMap = qsUserService.modifyConference(conferenceId,
					                                   qsUid,
					                                   newEntity.getName(),
					                                   min+"",
					                                   date1,
					                                   siteUrl);
			
			if("0".equals(qsMap.get("success"))) {
				QSMeetingInfo oldQsInfo = qsMeetingService.findOne(qsId);
				oldQsInfo.setEmceeUser(newEntity.getCreatedBy());
				oldQsInfo.setConferenceId(qsMap.get("conferenceId")+"");
				oldQsInfo.setPcode1(qsMap.get("pcode1")+"");
				oldQsInfo.setPcode2(qsMap.get("pcode2")+"");

				qsMeetingService.saveQSMeetingInfo(oldQsInfo);
				logger.debug("--"+newEntity.getName()+"-全时会议预约修改成功！---");
			}else {
				res = "update false:"+qsMap.get("err");
			}
		}
		return res;
	}
	/**
	 * 取消网络会议
	 * @return
	 */
	public void delQSMeeting(String meetingApplyId,
					            String oldcreateBy,
					            String token) throws Exception {
		logger.debug("-----------------delQSMeeting-------------------");
        String siteUrl = getQSSysINfo(token);
        logger.debug("siteUrl:"+siteUrl);
        
        String qsUid = qsUserService.getQsUserAcc(oldcreateBy);
        
        if(qsUid!=null && !"".equals(qsUid)) {
	        Map qsInfo = qsMeetingService.getQsMeetingInfoByMeetingId(meetingApplyId);
		     
	        if(qsInfo!=null && qsInfo.get("conferenceId")!=null) {
				String conferenceId = qsInfo.get("conferenceId")+"";
		
		        //取消Qs
		        this.qsUserService.cancelConference(conferenceId,qsUid,siteUrl);
		        QSMeetingInfo info = new QSMeetingInfo();
		        info.setMeetingApplyId(meetingApplyId);
		        //删除记录
		        this.qsMeetingService.delQSMeetingInfo(meetingApplyId);
	        }else {
	        	logger.debug("---------delQSMeeting--qsMeetingInfo is null-------------");
	        }
        }else {
        	logger.debug("---------delQSMeeting--qsUid is null-------------");
        }
    }
	
	/**
	 * 批量取消网络会议
	 * @return
	 */
	public void delQSMeetings(String token,String...  meetingApplyIds){
		logger.debug("-----------------delQSMeetings-------------------");
        String siteUrl = getQSSysINfo(token);
        logger.debug("siteUrl:"+siteUrl);
        
        for (String id : meetingApplyIds) {
    		ApplyRecord record = this.service.findOne(id);
			if(record == null) continue;
			String qsUid = qsUserService.getQsUserAcc(record.getCreatedBy());
			if(qsUid == null||"".equals(qsUid)) continue;
    		
			Map qsInfo = qsMeetingService.getQsMeetingInfoByMeetingId(id);
			if(qsInfo == null) continue;
			String conferenceId = qsInfo.get("conferenceId")+"";
			//取消Qs
	        this.qsUserService.cancelConference(conferenceId,qsUid,siteUrl);
		}

    }
	/**
	 * 获取系统管理配置的全时参数
	 * @param token
	 * @return
	 */
	public String getQSSysINfo(String token) {
		
        String siteUrl = "";//"zhongkeyungu.quanshi.com"
		
		RestClient restClient = new RestClient(true);
		Map paramMap = new HashMap();
		String json = restClient.get("/w/system/basic/sysNetmeetingSetting", token, paramMap);
		logger.debug("sysNetmeetingSetting-json:"+json);
		Map<String,Object> map = JsonUtils.readValue(json);
        if(map.get("type").toString().equals("success")){
            // 返回结果
            Map<String, Object> dataMap = (Map<String, Object>) map.get("data");
            Map<String, Object> confSettingMap = (Map<String, Object>) dataMap.get("confSettingMap");
            siteUrl =  confSettingMap.get("siteUrlVal")+"";
        }
        return siteUrl;
    }
}



